package org.qloudgen.borg.pages;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.AjaxSelfUpdatingTimerBehavior;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.util.time.Duration;
import org.qloudgen.borg.metadb.DefaultImpl;
import org.qloudgen.borg.pages.model.LogModel;

@SuppressWarnings("unchecked")
public class TaskLogPage extends WebPage{

	/**
	 * @Author youngeryoyo
	 * youngeryoyo@gmail.com
	 */

	private static final long serialVersionUID = 1L;
	private transient PageParameters pp;
	private transient String log = "";
	private transient LogModel logModel = new LogModel();
	
	@SuppressWarnings({ "rawtypes" })
	public TaskLogPage(PageParameters pageParameters){
		
		super();
		this.pp = pageParameters;
		
		// get task no 
		final String taskNo = this.pp.get("taskNo").toString();
		
		// get new log from metadb
		log = DefaultImpl.getTaskNewLog(taskNo);
		
		Form form = new Form("form",new CompoundPropertyModel<LogModel>(logModel.setLog(log)));
		this.add(form);
		
		final TextArea logInfo = new TextArea("log");
		logInfo.setOutputMarkupId(true);
		logInfo.add(new AjaxSelfUpdatingTimerBehavior(Duration.seconds(2)){

			private static final long serialVersionUID = 1L;

			@Override
			protected  void	onPostProcessTarget(AjaxRequestTarget target)  {
				
				// get new log from metadb
				log = DefaultImpl.getTaskNewLog(taskNo);
				if (log == null) return;
				
				logModel.setLog(log);
				
				target.add(logInfo);
				
			}
		});
		
		form.add(logInfo);
		
		form.add(new AjaxButton("refresh"){
			
			private static final long serialVersionUID = 1L;
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				
				// get new log from metadb
				log = DefaultImpl.getTaskNewLog(taskNo);
				logModel.setLog(log);
				
				target.add(logInfo);
			}
		});	
		
		Button cancel = new Button ("return"){
			private static final long serialVersionUID = 1L;
			public void onSubmit() {
				setResponsePage(TaskListPage.class);
			}
		};
		form.add(cancel);
		cancel.setDefaultFormProcessing(false);
	}
}
